<template>
  <div class="booking-details-page">
    <h2>预订详情</h2>
    <BookingDetailsCard v-if="bookingDetails" :bookingDetails="bookingDetails" />
    <div v-else class="loading-message">
      加载预订详情...
    </div>
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>

    <div v-if="bookingDetails && bookingDetails.paymentStatus !== 1 && bookingDetails.paymentStatus !== 2 && bookingDetails.paymentStatus !== 3" class="payment-section">
      <h3>支付倒计时</h3>
      <p>请在 <span class="countdown">{{ formatTime(countdown) }}</span> 内完成支付。</p>
      <div class="payment-actions">
        <button @click="handlePayment" class="pay-button success">立即支付</button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute } from 'vue-router';
import { getOrderById, getTimeDifference, payOrder } from '@/apis/orders';
import { useBookingTempStore } from '@/stores/bookingTemp';
import BookingDetailsCard from '@/components/bookings/BookingDetailsCard.vue';

const route = useRoute();
const bookingDetails = ref(null);
const errorMessage = ref('');
const bookingTempStore = useBookingTempStore();
const countdown = ref(0);
let countdownInterval = null;

const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

const startCountdown = async (orderId) => {
  if (countdownInterval) clearInterval(countdownInterval);

  try {
    const response = await getTimeDifference(orderId);
    if (response.code === 200 && response.data) {
      const timeParts = response.data.split(':');
      const minutes = parseInt(timeParts[0]);
      const seconds = parseInt(timeParts[1]);
      countdown.value = minutes * 60 + seconds;

      if (countdown.value > 0) {
        countdownInterval = setInterval(() => {
          if (countdown.value > 0) {
            countdown.value--;
          } else {
            clearInterval(countdownInterval);
            alert('支付时间已到，订单已自动取消。');
            // Optionally, update bookingDetails status or refresh page
          }
        }, 1000);
      } else {
        alert('订单已过期或已支付。');
      }
    } else {
      errorMessage.value = response.msg || '未能获取倒计时信息。';
    }
  } catch (error) {
    console.error('Failed to get time difference:', error);
    errorMessage.value = '获取倒计时失败，请稍后再试。';
  }
};

const handlePayment = async () => {
  if (!bookingDetails.value || !bookingDetails.value.orderId) {
    alert('没有可支付的订单。');
    return;
  }

  try {
    const response = await payOrder(bookingDetails.value.orderId);
    if (response.code === 200) {
      alert('支付成功！');
      clearInterval(countdownInterval);
      // Update bookingDetails to reflect paid status
      bookingDetails.value.paymentStatus = 1; // Assuming 1 means paid
    } else {
      alert(`支付失败: ${response.msg}`);
    }
  } catch (error) {
    console.error('Payment failed:', error);
    alert('支付处理失败，请稍后再试。');
  }
};

onMounted(async () => {
  const orderId = route.params.id;
  if (!orderId) {
    errorMessage.value = '缺少订单ID。';
    return;
  }

  try {
    if (bookingTempStore.tempBookingDetails) {
      bookingDetails.value = bookingTempStore.tempBookingDetails;
      bookingTempStore.clearTempBookingDetails(); // Clear after use
    } else {
      // Fallback to fetching if navigated directly or page refreshed
      const response = await getOrderById(orderId);
      if (response.code === 200 && response.data) {
        bookingDetails.value = response.data;
      } else {
        errorMessage.value = response.msg || '未能加载订单详情。';
      }
    }

    // Start countdown if bookingDetails are available and payment is pending (assuming not 1, 2, or 3 means pending)
    if (bookingDetails.value && bookingDetails.value.paymentStatus !== 1 && bookingDetails.value.paymentStatus !== 2 && bookingDetails.value.paymentStatus !== 3) {
      startCountdown(orderId);
    }

    console.log('Booking Details:', bookingDetails.value);

  } catch (error) {
    console.error('Failed to fetch booking details:', error);
    errorMessage.value = '加载订单详情失败，请稍后再试。';
  }
});

onUnmounted(() => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
  }
});
</script>
<style scoped>
.booking-details-page {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 2rem;
}

.loading-message, .error-message {
  text-align: center;
  padding: 1rem;
  margin-top: 1rem;
  border-radius: 4px;
}

.loading-message {
  background-color: #e0f7fa;
  color: #00796b;
}

.error-message {
  background-color: #ffebee;
  color: #d32f2f;
  border: 1px solid #ef9a9a;
}

.payment-section {
  background-color: #f0f8ff;
  border: 1px solid #cce5ff;
  border-radius: 8px;
  padding: 1.5rem;
  margin-top: 2rem;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.payment-section h3 {
  color: #0056b3;
  margin-top: 0;
  margin-bottom: 1rem;
}

.payment-section .countdown {
  font-size: 2rem;
  font-weight: bold;
  color: #dc3545;
  margin-bottom: 1rem;
  display: block;
}

.payment-actions .pay-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1.1rem;
  margin: 0 0.5rem;
  transition: background-color 0.3s ease;
}

.payment-actions .success {
  background-color: #28a745;
  color: #fff;
}

.payment-actions .success:hover {
  background-color: #218838;
}
</style>
